package com.cy.pj.sys.service.impl;

import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.pojo.CheckBox;
import com.cy.pj.common.pojo.PageObject;
import com.cy.pj.sys.dao.SysRoleDao;
import com.cy.pj.sys.dao.SysRoleMenuDao;
import com.cy.pj.sys.pojo.SysRole;
import com.cy.pj.sys.pojo.SysRoleMenu;
import com.cy.pj.sys.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Autowired
    private SysRoleDao sysRoleDao;

    @Autowired
    private SysRoleMenuDao sysRoleMenuDao;

    @Override
    public PageObject<SysRole> findPageObjects(String name, Integer pageCurrent) {
        //1.对参数进行校验
        if(pageCurrent==null || pageCurrent<1){
            throw new IllegalArgumentException("当前页码值无效");
        }
        //2.查询总记录数并进行校验
        int rowCount = sysRoleDao.getRowCount(name);
        if(rowCount==0){
            throw new ServiceException("没有找到对应记录");
        }
        //3.查询当前页记录
        int pageSize=2;
        int startIndex=(pageCurrent-1)*pageSize;
        List<SysRole> records = sysRoleDao.findPageObjects(name, startIndex, pageSize);
        //4.对查询结果进行封装并返回
        return new PageObject<>(pageCurrent, pageSize, rowCount, records);
    }

    @Override
    public int saveObject(SysRole entity, Integer[] menuIds) {
        int rows = sysRoleDao.insertObject(entity);
        sysRoleMenuDao.insertObjects(entity.getId(), menuIds);
        return rows;
    }

    @Override
    public SysRoleMenu findById(Integer id) {
        SysRoleMenu roleMenu = sysRoleDao.findById(id);
        return roleMenu;
    }


//    @Override
//    public SysRoleMenu findById(Integer id) {
//        SysRoleMenu roleMenu = sysRoleDao.findById(id);
//        List<Integer> menuIds = sysRoleMenuDao.findMenuIdsByRoleId(id);
//        roleMenu.setMenuIds(menuIds);
//        return roleMenu;
//    }

    @Override
    public int updateObject(SysRole entity, Integer[] menuIds) {
        sysRoleDao.updateObject(entity);
        sysRoleMenuDao.deleteObjectsByRoleId(entity.getId());
        sysRoleMenuDao.insertObjects(entity.getId(), menuIds);
        return 0;
    }

    @Override
    public int doDeleteObject(Integer id) {
        return sysRoleDao.doDeleteObject(id);
    }

    @Override
    public List<CheckBox> findObjects() {
        return sysRoleDao.findObjects();
    }
}
